package com.collect.tanzania.zhiUtils.zhiVersion;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class ZHIVersionClient {

    private static OkHttpClient mOkHttpClient = null;

    public static void startDownload(final String url,
                                     final ZHIVersionProgressListener listener) {
        try {
            //初始化
            if (mOkHttpClient == null) {
                mOkHttpClient = new OkHttpClient.Builder()
                        .connectTimeout(30000, TimeUnit.MILLISECONDS)
                        .readTimeout(30000, TimeUnit.MILLISECONDS)
                        .writeTimeout(30000, TimeUnit.MILLISECONDS).build();
            }

            //增加拦截器
            OkHttpClient client = mOkHttpClient.newBuilder().addNetworkInterceptor(chain -> {
                Response response = chain.proceed(chain.request());
                return response.newBuilder().body(new ZHIVersionResBody(response.body(), listener)).build();
            }).build();
            Request request = new Request.Builder().url(url).build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {
                }

                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                    InputStream inputStream = Objects.requireNonNull(response.body()).byteStream();
                    FileOutputStream fos = new FileOutputStream(new File(ZHIVersionIMPL.getApkSavePath()));
                    int len;
                    byte[] buffer = new byte[2048];
                    while (-1 != (len = inputStream.read(buffer))) {
                        fos.write(buffer, 0, len);
                    }
                    fos.flush();
                    fos.close();
                    inputStream.close();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
